package com.wish233.wiliwilisearch.mq;

import cn.hutool.core.bean.BeanUtil;
import com.rabbitmq.client.Channel;
import com.wish233.wiliwiliapi.domain.vo.VideoChange;
import com.wish233.wiliwiliapi.domain.vo.VideoVO;
import com.wish233.wiliwilisearch.domain.esdto.VideoEsDTO;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Map;

import static com.wish233.wiliwilicommon.constants.MqConstant.DLX_EXCHANGE;
import static com.wish233.wiliwilicommon.constants.MqConstant.DLX_ROUTING_KEY;
import static com.wish233.wiliwilisearch.mq.MqConstant.*;

/**
 * @author WHH
 */
@Service
public class SyncListener {

    @Resource
    private ElasticsearchRestTemplate restTemplate;

    @SneakyThrows
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = ES_SYNC_MYSQL_QUEUE, durable = "true", arguments = {
                            @Argument(name = "x-dead-letter-exchange", value = DLX_EXCHANGE), // 设置死信交换机
                            @Argument(name = "x-dead-letter-routing-key", value = DLX_ROUTING_KEY),
                            @Argument(name = "x-message-ttl", value = "300000", type = "java.lang.Long")// 设置死信路由键
                    }),
                    exchange = @Exchange(name = ES_SYNC_MYSQL_EXCHANGE),
                    key = ES_SYNC_MYSQL_ROUTING_KEY),
            ackMode = "MANUAL")
    public void handleVideoChange(VideoChange change, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        Object entity = change.getEntity();
        Integer changeType = change.getChangeType();
        if (changeType == 1) {
            VideoEsDTO videoEsDTO = VideoEsDTO.vo2EsDTO(BeanUtil.fillBeanWithMap((Map<?, ?>) entity, new VideoVO(), false, true));
            restTemplate.save(videoEsDTO);
        } else if (changeType == 2) {
            restTemplate.delete(String.valueOf(entity), VideoEsDTO.class);
        }
        channel.basicAck(deliveryTag, false);
    }
}
